package controllers

import (
	"NewEdu/utils"
	"fmt"
	"strings"
	"time"

	beego "github.com/beego/beego/v2/server/web"
)

type FileController struct {
	beego.Controller
}

// UploadFile ...
// @Title 文件上传
// @Description 文件上传
// @Param	Authorization	header	string	true	" Token"
// @Param	channel		path 	string	true		"模块名字，分为log .."
// @Param	file		formData 	file	true		"相关资源"
// @Success 200 {object} models.TDepart
// @Failure 403 :id is empty
// @router /upload/:channel [post]
func (c *FileController) UploadFile() {
	channel := c.Ctx.Input.Param(":channel")
	_, h, err := c.GetFile("file") //获取上传的文件
	if err != nil {
		c.Data["json"] = utils.Export(500, c.Ctx.Input.URI(), err.Error())
		c.ServeJSON()
		return
	}
	filenames := strings.Split(h.Filename, ".")
	ext := filenames[len(filenames)-1]

	url := "upload/" + channel + "/" + fmt.Sprintf("%v.%s", time.Now().UnixNano(), ext)
	err = c.SaveToFile("file", utils.UploadDir+url)
	if err != nil {
		c.Data["json"] = utils.Export(500, url, err.Error())
		c.ServeJSON()
		return
	}

	c.Data["json"] = utils.Export(1000, "ok", "/"+url)

	c.ServeJSON()
}
